package com.qujia.station.controller;

import com.alibaba.fastjson.JSONObject;
import com.qujia.common.constant.HttpStatus;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.page.PageDomain;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.core.page.TableSupport;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.station.domain.MarketActivity;
import com.qujia.station.domain.Station;
import com.qujia.station.service.IStationService;
import com.qujia.station.service.MarketActivityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@RestController
@RequestMapping("/nonMarket")
@Slf4j
@Api(value = "非油促销活动")
public class MarketActivityController extends BaseController {

    @Autowired
    public MarketActivityService marketActivityService;

    @Autowired
    private IStationService stationService;

    @PostMapping("/activity/list")
    @ApiOperation(value = "查看促销活动列表",httpMethod = "POST")
    public TableDataInfo selectMarketActivityList(@RequestBody MarketActivity marketActivity){
        if(Objects.isNull(marketActivity) || Objects.isNull(marketActivity.getPageNum())
                || Objects.isNull(marketActivity.getPageSize())){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("请求参数异常");
            rspData.setRows(null);
            rspData.setTotal(0);
            return rspData;
        }
        PageDomain pageDomain = TableSupport.buildPageRequest();
        pageDomain.setPageNum(marketActivity.getPageNum());
        pageDomain.setPageSize(marketActivity.getPageSize());
        marketActivity.setStationIdList(getStationIdList(marketActivity));
        log.info("selectMarketActivityList查看促销活动列表 请求参数 ：[{}]", JSONObject.toJSONString(marketActivity));
        startPage(pageDomain);
        List<MarketActivity> marketActivitieList = marketActivityService.selectMarketActivityList(marketActivity);
        if(CollectionUtils.isEmpty(marketActivitieList)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("暂无数据");
            rspData.setRows(null);
            rspData.setTotal(0);
            return rspData;
        }
        log.info("selectMarketActivityList查看促销活动列表 响应结果：[{}]",marketActivitieList.size());
        return getDataTable(marketActivitieList);
    }

    private List<Long> getStationIdList(MarketActivity marketActivity){
        List<Long> stationIdList = new ArrayList<>();
        if(Objects.nonNull(marketActivity.getStationId())){
            stationIdList.add(marketActivity.getStationId());
        } else if(Objects.nonNull(marketActivity.getEnterpriseId())){
            List<Station> stationList = stationService.getStationByEnterpriseId(marketActivity.getEnterpriseId());
            for (Station station : stationList) {
                stationIdList.add(station.getStationId());
            }
        }
        return stationIdList;
    }


    @PostMapping("/activity/add")
    @ApiOperation(value = "新增促销活动",httpMethod = "POST")
    public AjaxResult addMarketActivity(@RequestBody MarketActivity marketActivity){
        if(Objects.isNull(marketActivity)){
            return AjaxResult.error("请求参数异常");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(Objects.isNull(user)){
            return AjaxResult.error("该账号不存在，请重新登录");
        }
        if(!judgeAccount(user)){
            return AjaxResult.error("该账号不能新增促销活动");
        }
        if(StringUtils.isEmpty(marketActivity.getMarketActivityName())){
            return AjaxResult.error("请求输入促销活动名称");
        }

        if(StringUtils.isEmpty(marketActivity.getMarketActivityType())){
            return AjaxResult.error("请求选择促销活动类型");
        }
        if(StringUtils.isEmpty(marketActivity.getAllOrPart())){
            return AjaxResult.error("请求选择参与商品范围");
        }
        if(Objects.isNull(marketActivity.getBeginTime())){
            return AjaxResult.error("请求选择开始时间");
        }
        if(Objects.isNull(marketActivity.getEndTime())){
            return AjaxResult.error("请求选择结束时间");
        }

        if(UserConstants.LEVEL_THREE.equals(user.getUserLevel())){
            marketActivity.setStationId(user.getStationId());
        }
        if(Objects.isNull(marketActivity.getStationId())){
            return AjaxResult.error("请求选择门店");
        }
        marketActivity.setCreateUser(user.getUserId());
        marketActivity.setUpdateTime(new Date());
        log.info("addMarketActivity 新增促销活动请求参数：[{}]", JSONObject.toJSONString(marketActivity));
        Long i = marketActivityService.saveMarketActivity(marketActivity);
        log.info("addMarketActivity 新增促销活动返回结果：[{}]", i);
        if(i <= 0){
            return AjaxResult.error("新增促销活动失败");
        }
        return AjaxResult.success();
    }

    // 只有油企、油站 账号可以增删改查 admin 只能查询
    private boolean judgeAccount(SysUser user){
        if(UserConstants.LEVEL_TWO.equals(user.getUserLevel()) || UserConstants.LEVEL_THREE.equals(user.getUserLevel())){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @PostMapping("/activity/update")
    @ApiOperation(value = "修改促销活动",httpMethod = "POST")
    public AjaxResult updateMarketActivity(@RequestBody MarketActivity marketActivity){
        if(Objects.isNull(marketActivity) || Objects.isNull(marketActivity.getMarketActivityId())){
            return AjaxResult.error("请求参数异常");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(Objects.isNull(user)){
            return AjaxResult.error("该账号不存在，请重新登录");
        }

        if(!judgeAccount(user)){
            return AjaxResult.error("该账号不能新增促销活动");
        }

        marketActivity.setUpdateTime(new Date());
        marketActivity.setUpdateUser(user.getUserId());
        log.info("修改促销活动 updateMarketActivity 请求参数:[{}]",JSONObject.toJSONString(marketActivity));
        int i = marketActivityService.updateMarketActivity(marketActivity);
        log.info("修改促销活动 updateMarketActivity 返回结果:[{}]",i);
        if(i <= 0){
            return AjaxResult.error("修改促销活动失败");
        }
        return AjaxResult.success();
    }

    @GetMapping("/activity/delete")
    @ApiOperation(value = "删除促销活动",httpMethod = "GET")
    public AjaxResult deleteMarketActivity(@RequestParam("marketActivityId") Long marketActivityId){
        if(Objects.isNull(marketActivityId)){
            return AjaxResult.error("请求参数异常");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(Objects.isNull(user)){
            return AjaxResult.error("该账号不存在，请重新登录");
        }

        if(!judgeAccount(user)){
            return AjaxResult.error("该账号不能删除促销活动");
        }
        log.info("删除促销活动 deleteMarketActivity 请求参数:[{}]",marketActivityId);
        int i = marketActivityService.deleteMarketActivity(marketActivityId);
        log.info("删除促销活动 deleteMarketActivity 响应结果:[{}]",marketActivityId);
        if(i <= 0){
            return AjaxResult.error("删除促销活动失败");
        }
        return AjaxResult.success();
    }

    @PostMapping("/activity/start")
    @ApiOperation(value = "启用停止促销活动",httpMethod = "POST")
    public AjaxResult enabledMarketActivity(@RequestBody MarketActivity marketActivity){
        if(Objects.isNull(marketActivity) || Objects.isNull(marketActivity.getMarketActivityId())
                || Objects.isNull(marketActivity.getIsEnabled())){
            return AjaxResult.error("请求参数异常");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(Objects.isNull(user)){
            return AjaxResult.error("该账号不存在，请重新登录");
        }

        if(!judgeAccount(user)){
            return AjaxResult.error("该账号不能启用停止促销活动");
        }
        marketActivity.setUpdateTime(new Date());
        marketActivity.setUpdateUser(user.getUserId());
        log.info("启用停止促销活动 enabledMarketActivity 请求参数:[{}]",JSONObject.toJSONString(marketActivity));
        int i = marketActivityService.updateEnabled(marketActivity);
        log.info("启用停止促销活动 enabledMarketActivity 响应结果:[{}]",i);
        if(i <= 0){
            return AjaxResult.error("启用停止促销活动失败");
        }
        return AjaxResult.success();
    }
}
